package com.doge.calcalbum.core

import android.content.Intent
import android.os.Build
import androidx.core.content.PermissionChecker
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.doge.calcalbum.utils.appContext

object PermissionUtil {

    private val callbacks = HashMap<Long, (Boolean) -> Unit>()

    fun requestPermissions(lifecycle: Lifecycle, vararg permissions: String, callback: (granted: Boolean) -> Unit) {
        if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
            return
        }

        val callbackId = System.currentTimeMillis()

        var isStopped = false
        lifecycle.addObserver(object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            fun onDestroy() {
                isStopped = true
                callbacks.remove(callbackId)
                lifecycle.removeObserver(this)
            }
        })

        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (!isStopped) {
                callback.invoke(true)
            }
            return
        }
        val granted = permissions.none { PermissionChecker.PERMISSION_GRANTED != PermissionChecker.checkSelfPermission(
            appContext, it) }
        if (granted) {
            if (!isStopped) {
                callback.invoke(true)
            }
            return
        }
        callbacks[callbackId] = callback
        calcPermissionRequiring = true
        appContext.startActivity(Intent(appContext, RequestPermissionActivity::class.java)
                .putExtra("callbackId", callbackId)
                .putExtra("permissions", permissions)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        )
    }


    internal fun notifyCallback(callbackId: Long, granted: Boolean) = callbacks.remove(callbackId)?.invoke(granted)

}